package batch.import_user;

import java.sql.*;
import java.io.*;
import java.net.URLEncoder;
import java.net.URL;
import java.net.HttpURLConnection;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.dbutils.*;
import org.apache.log4j.*;

import batch.common.secui.*;
import batch.common.db.ConnectionManager;
import batch.common.util.*;

public class importDataForEsp
{
    private final String TRPLKEY     = "QWERTYUIOP!@#$%^&*()aaaa";

    private final String TABLE_NAME  = "G_ESP_IMPORT_TEMP";
    private final String MEMBERGBN   = "10563104";

    private final String LANGUAGE    = "ESP";
    private final String COUNTRY     = "0102057";
    private final String REG_COUNTRY = "0102057";
    private final String HP_BRAND    = "0103001";
    private final String NEWS_LETTER = "Y";
    private final String GRADE       = "1";

    public static void main(String[] args)
    {
        Logger.getLogger("import_user.importDataForEsp").info("( * ) Start.");

        importDataForEsp obj = new importDataForEsp();
        obj.init();

        Logger.getLogger("import_user.importDataForEsp").info("( * ) End.");
    }

    public void init() {
        StringBuffer sQuery = new StringBuffer()
                             .append("SELECT SEQ                                  \n")
                             .append("     , USERID                               \n")
                             .append("     , PASSWD                               \n")
                             .append("     , EMAIL                                \n")
                             .append("     , FNAME                                \n")
                             .append("     , BIRTH                                \n")
                             .append("     , LNAME                                \n")
                             .append("     , GENDER                               \n")
                             .append("  FROM " + TABLE_NAME + "                   \n")
                             .append(" WHERE EMAIL IS NOT NULL                    \n");
                             //.append(" WHERE GUBN IN ('7', '97 id', '97 passwd') \n");

        StringBuffer sbParameters = new StringBuffer();
        String currentServer = (Conf.getConf("server").indexOf("www") >= 0) ? "www" : "dev";

        String seq       = "";
        String id        = "";
        String passwd    = "";
        String birthday  = "";
        String firstname = "";
        String lastname  = "";
        String email     = "";
        String gender    = "";

        String strResult = "";
        String strLine   = "";
        int    i = 0;

        Connection conn  = null;
        Statement  stmt  = null;
        ResultSet  rs    = null;

        BufferedReader in = null;
        PrintWriter pwServelt = null;

        try{
            TripleDES tplDES = new TripleDES(TRPLKEY);

            conn = ConnectionManager.getConnection();
            conn.setAutoCommit(true);
            stmt= conn.createStatement();
            rs = stmt.executeQuery(sQuery.toString());

            QueryRunner qRunner = new QueryRunner();

            URL urlOpen = new URL("http://" + currentServer + ".samsungmobile.com/integration/user_profile/simple_register_user");

            while (rs.next()) {
                i++;

                seq       = ObjectUtils.toString(rs.getObject(1));
                id        = tplDES.encrypt(ObjectUtils.toString(rs.getObject(2)));
                passwd    = tplDES.encrypt(ObjectUtils.toString(rs.getObject(3)));
                email     = tplDES.encrypt(ObjectUtils.toString(rs.getObject(4)));
                firstname = new String(ObjectUtils.toString(rs.getObject(5)).getBytes("UTF-8"), "ISO-8859-1");
                lastname  = new String(ObjectUtils.toString(rs.getObject(7)).getBytes("UTF-8"), "ISO-8859-1");
                birthday  = ObjectUtils.toString(rs.getObject(6));
                gender    = ObjectUtils.toString(rs.getObject(8));


                HttpURLConnection httpUrlConn = (HttpURLConnection)urlOpen.openConnection();
                httpUrlConn.setRequestMethod("POST");
                httpUrlConn.setDoOutput(true);
                pwServelt = new PrintWriter(httpUrlConn.getOutputStream());

                //encode the message
                sbParameters.setLength(0);
                sbParameters.append("id="          ).append(URLEncoder.encode(id         , "ISO-8859-1"))
                            .append("&passwd="     ).append(URLEncoder.encode(passwd     , "ISO-8859-1"))
                            .append("&email="      ).append(URLEncoder.encode(email      , "ISO-8859-1"))
                            .append("&fname="      ).append(URLEncoder.encode(firstname  , "ISO-8859-1"))
                            .append("&lname="      ).append(URLEncoder.encode(lastname   , "ISO-8859-1"))
                            .append("&birthday="   ).append(URLEncoder.encode(birthday   , "ISO-8859-1"))
                            .append("&country="    ).append(URLEncoder.encode(COUNTRY    , "ISO-8859-1"))
                            .append("&reg_country=").append(URLEncoder.encode(REG_COUNTRY, "ISO-8859-1"))
                            .append("&hp_brand="   ).append(URLEncoder.encode(HP_BRAND   , "ISO-8859-1"))
                            .append("&membergbn="  ).append(URLEncoder.encode(MEMBERGBN  , "ISO-8859-1"))
                            .append("&gender="     ).append(URLEncoder.encode(gender     , "ISO-8859-1"))
                            .append("&language="   ).append(URLEncoder.encode(LANGUAGE   , "ISO-8859-1"))
                            .append("&news_letter=").append(URLEncoder.encode(NEWS_LETTER, "ISO-8859-1"))
                            .append("&grade="      ).append(URLEncoder.encode(GRADE      , "ISO-8859-1"));


                //send the encoded message
                pwServelt.print(sbParameters);

                if(pwServelt != null) try { pwServelt.close(); } catch(Exception se) {}

                in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream()));

                while ((strLine = in.readLine()) != null) {
                    strResult = strLine.trim();
                }

                if(in != null) try { in.close(); } catch(Exception se) {}

                sQuery.setLength(0);
                sQuery.append("UPDATE " + TABLE_NAME + "         \n")
                      .append("   SET GUBN = '" + strResult + "' \n")
                      .append(" WHERE SEQ = '" + seq + "'        \n");

                qRunner.update(conn, sQuery.toString());

                if( (i%500) == 0){
                    Logger.getLogger("import_user.importDataForEsp").info("here we are == " + i);
                }
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
            Logger.getLogger("import_user.importDataForEsp").info(ex.toString());
        }
        finally{
            if(pwServelt != null) try { pwServelt.close(); } catch(Exception se) {}
            if(in        != null) try { in.close();        } catch(Exception se) {}
            if(rs        != null) try { rs.close();        } catch(Exception se) {}
            if(stmt      != null) try { stmt.close();      } catch(Exception se) {}
            if(conn      != null) try { conn.close();      } catch(Exception se) {}
        }
    }
}
